<?php
namespace Home\Controller;
use Home\Controller;
/**
* 文章分类管理
*/
class CateController extends AdminController
{
	/**
	 * 分类首页
	 * @return [type] [description]
	 */
	public function cateManage($order = 'id',$p = 1)
	{
		$admininfo = $this->checkLogin();
		$this->assign('admininfo', $admininfo);

		$cate = M('cate');
		$res = $cate
			->field('bg_cate.id,bg_cate.cate,bg_article.cateid,count(*)')
			->join('bg_article ON bg_cate.id = bg_article.cateid','left')
			->group('bg_cate.cate')
			->order($order)
			->page($p,10)
			->select();
		$this->assign('res', $res);
		$count = $cate->count();
		$page = new \Think\Page($count,10);
		$page->setConfig('prev','<i class="fa fa-chevron-left"></i>');
		$page->setConfig('next','<i class="fa fa-chevron-right"></i>');
		$show = $page->show();
		$this->assign('page', $show);
		$this->display();
	}
	/**
	 * 添加分类
	 */
	public function addCate()
	{
		if (IS_POST) {
			$cate = D('Cate');
			if (!$cate->create()) {
				alertMes($cate->getError(), U('cate/cateManage'));
			} else {
				$arr['cate'] = I('post.cate');
				$res = $cate->add($arr);
				if ($res) {
					alertMes('添加成功', U('cate/cateManage'));
				} else {
					alertMes('添加失败', U('cate/cateManage'));
				}
			}
		} else {
			$this->redirect('/cate/cateManage');
		}
	}
	/**
	 * 编辑分类
	 * @return [type] [description]
	 */
	public function editCate()
	{
		if (IS_POST) {
			$cate = D('Cate');
			if (!$cate->create()) {
				alertMes($cate->getError(), U('cate/cateManage'));
			} else {
				$arr['id'] = I('post.id');
				$arr['cate'] = I('post.cate');
				$res = $cate->save($arr);
				if ($res) {
					alertMes('修改成功', U('cate/cateManage'));
				} else {
					alertMes('修改失败', U('cate/cateManage'));
				}
			}
		} else {
			$this->redirect('/cate/cateManage');
		}
	}
	/**
	 * 删除分类
	 * @param  int $id [description]
	 * @return [type]     [description]
	 */
	public function delCate($id)
	{
		$cate = D('Cate');
		$article = M('Article');
		$resArt = $article->where('cateid=' . $id)->field('cateid')->find();
		if ($resArt) {
			alertMes('分类下有文章，无法删除', U('cate/cateManage'));
		} else {
			$res = $cate->where('id=' . $id)->delete();
			if ($res) {
				alertMes('删除成功', U('cate/cateManage'));
			} else {
				alertMes('删除失败', U('cate/cateManage'));
			}
		}
	}
	/**
	 * 转移文章
	 * @return [type] [description]
	 */
	public function moveCate()
	{
		$article = M('Article');
		$id = I('post.id');
		$data['cateid'] = I('post.newcateid');
		$res = $article->where('cateid=' . $id)->save($data);
		if ($res) {
			alertMes('转移成功', U('cate/cateManage'));
		} else {
			alertMes('转移失败', U('cate/cateManage'));
		}
	}
}